package com.szosen.jkzj.activity;

import android.annotation.SuppressLint;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.szosen.application.MyApplication;
import com.szosen.database.DBService;
import com.szosen.database.HealthRecord;
import com.szosen.database.UploadRecord;
import com.szosen.jkzj.R;
import com.szosen.json.database.ArchiveBean;
import com.szosen.util.ChoiceEditText;
import com.szosen.util.ToastTool;
import com.szosen.util.Tools;
import com.szosen.web.UploadContant;

@SuppressLint("InflateParams")
public abstract class BaseActivity extends FragmentActivity {

    /***
     * 用于判断时属于哪一个activity的标记。
     */
    public static final String ACTIVITY_FLAG = "activity_flag";
    public static final String ACTIVITY_FLAG_JKDA = "jkda";
    public static final String ACTIVITY_FLAG_MBGY = "mbgy";
    public static final String ACTIVITY_FLAG_JKTJ = "jktj";
    public static final String ACTIVITY_FLAG_GGWS = "ggws";
    public Context context;
    public static final int WHAT_UPLOAD_SUCCESS = 0x66;
    public static final int WHAT_UPLOAD_FAILED = 0x44;
    public static final int WHAT_UPLOAD_ERROR = 0x99;
    public Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case WHAT_UPLOAD_SUCCESS:
                    ToastTool.showLong(context, "数据上传成功！");
                    finish();
                    break;
                case WHAT_UPLOAD_FAILED:
                    String data = (String) msg.obj;
                    ToastTool.showLong(context, "数据上传错误，" + data + "!");
                    break;
                case WHAT_UPLOAD_ERROR:
                    ToastTool.showLong(context, "数据上传错误，已离线保存！");
                default:
                    break;
            }
        }

        ;
    };

    /***
     * 返回一个对象
     *
     * @param title
     * @param message
     * @return
     */
    protected AlertDialog showDialog(String title, String message, boolean setOK) {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
        if (setOK) {
            dialogBuilder.setNegativeButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
        }
        dialogBuilder.setCancelable(false);
        dialogBuilder.setTitle(title).setMessage(message);
        AlertDialog dialog = dialogBuilder.create();
        return dialog;
    }

    /***
     * 请求服务器失败
     */
    public void requestError(String time) {
        mHandler.obtainMessage(WHAT_UPLOAD_ERROR).sendToTarget();
        UploadRecord ur = new UploadRecord();
        ur.setTime(time);
        ur.setUploadState(UploadContant.UPLOADFAILED);
        ur.setUploadMessage("网络错误");
        DBService.add(ur);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
            // return true;
        } else if (keyCode == KeyEvent.KEYCODE_MENU) {

        } else if (keyCode == KeyEvent.KEYCODE_HOME) {
            // return true;
            // 由于Home键为系统键，此处不能捕获，需要重写onAttachedToWindow()
        }
        return super.onKeyDown(keyCode, event);
    }

    public void checkResult(String response, String time) {
        if (!TextUtils.isEmpty(response)) {
            UploadRecord ur = new UploadRecord();
            ur.setTime(time);
            // 如果成功了。
            if (response.contains("success")) {
                mHandler.obtainMessage(WHAT_UPLOAD_SUCCESS).sendToTarget();
                ur.setUploadState(UploadContant.UPLOADOK);
                int start = response.indexOf("<returntext>");
                start += 12;
                int end = response.indexOf("</returntext>");
                if (start >= 0 && end >= 0 && start < end) {
                    String data = response.substring(start, end);
                    ur.setUploadMessage(data);
                } else {
                    ur.setUploadMessage("");
                }
            } else if (response.contains("error")) {
                // 未上传
                ur.setUploadState(UploadContant.UPLOADFAILED);
                // <returntext>上传成功！</returntext>
                int start = response.indexOf("<returntext>");
                start += 12;
                int end = response.indexOf("</returntext>");
                if (start >= 0 && end >= 0 && start < end) {
                    String data = response.substring(start, end);
                    mHandler.obtainMessage(WHAT_UPLOAD_FAILED, data)
                            .sendToTarget();
                    ur.setUploadMessage(data);
                } else {
                    ur.setUploadMessage("");
                    mHandler.obtainMessage(WHAT_UPLOAD_FAILED, "")
                            .sendToTarget();
                }
            }
            DBService.add(ur);
        }
    }

    /***
     * 通过EditText获取文本内容
     *
     * @return
     */
    public String getTextByEt(EditText et) {
        if (et == null) {
            return "";
        }
        String text = et.getText().toString().trim();
        if (TextUtils.isEmpty(text))
            return "";
        else {
            return text;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        context = this;
        DBService.getInstance(context);
    }

    /***
     * 通过EditText的id，获取文本内容
     *
     * @param id
     * @return
     */
    public String getTextById(int id) {
        EditText et = (EditText) findViewById(id);
        if (et == null) {
            return "";
        }
        String text = et.getText().toString();
        if (TextUtils.isEmpty(text))
            return "";
        else {
            return text;
        }
    }

    /**
     * 设置id对应的EditText的string为text
     *
     * @param id
     * @param text
     */
    protected void setText(int id, String text) {
        if (text != null)
            ((EditText) findViewById(id)).setText(text);
    }

    protected void setChoiceEditText(int id, String[] items, String editableItem) {
        ChoiceEditText cet = (ChoiceEditText) findViewById(id);
        cet.setFixItems(items);
        if (editableItem != null)
            cet.setEditableItem(editableItem);
    }

    /**
     * 给大标题设置内容
     */
    public void setTitleContent(String title) {
        TextView tv_title = (TextView) findViewById(R.id.main_all_tv_title);
        if (tv_title != null) {
            tv_title.setText(title);
        }
    }

    private static String idCard = "";
    private static String sName = "";
    private static String sSex = "";
    private static String sHeight = "";

    public static void setHeight(String height) {
        BaseActivity.sHeight = height;
    }

    public static String getHeight() {
        return sHeight;
    }

    public static void setSex(String sex) {
        BaseActivity.sSex = sex;
    }

    public static String getSex() {
        return getArchiveBean().getSex();
    }

    public static void setIdCard(String idCard) {
        BaseActivity.idCard = idCard;
    }

    public static String getIdCard() {
        // System.out.println("baseactivity获取idcard"+idCard);
        return getArchiveBean().getIdcard();
    }

    public static void setName(String name) {
//        BaseActivity.sName = name;
    }

    public static String getName() {
        return getArchiveBean().getName();
    }

    public static HealthRecord healthRecord;

    public static void setHealthRecord(HealthRecord healthRecord) {
        BaseActivity.healthRecord = healthRecord;
    }

    public static HealthRecord getHealthRecord() {
        if (healthRecord == null) {
            healthRecord = new HealthRecord();
        }
        if (archiveBean != null) {
            healthRecord.setPersonName(archiveBean.getName());
            healthRecord.setIdCard(archiveBean.getIdcard());
            healthRecord.setSexCode("男".equals(archiveBean.getSex()) ? "1"
                    : "2");

        }
        return healthRecord;
    }

    public static void setArchiveBean(ArchiveBean archiveBean) {
        BaseActivity.archiveBean = archiveBean;
    }

    private static ArchiveBean archiveBean;

    public static ArchiveBean getArchiveBean() {
        if (archiveBean == null) {
            return new ArchiveBean();
        }
        return archiveBean;
    }

    @SuppressLint("ResourceAsColor")
    @Override
    protected void onResume() {
        super.onResume();
        TextView tv_service_state = (TextView) findViewById(R.id.tv_server_state);
        if (tv_service_state != null) {
            if (MyApplication.isConnected()) {
                tv_service_state.setTextColor(R.color.color_service_connected);
                tv_service_state.setText("已连接");
            } else {
                tv_service_state
                        .setTextColor(R.color.color_service_noconnected);
                tv_service_state.setText("未连接");
            }
        }
    }

    public static void setJktjTime(String time) {
        sTime = time;
    }

    public static String sTime = "";

    public static String getJktjTime() {
        return sTime;
    }

    public static String jkdaTime = "";

    public static void setJKDATime(String time) {
        jkdaTime = time;
    }

    public static String getJKDATime() {
        return jkdaTime;
    }

}
